const app = new Vue({
    el: '#app',
    data() {
        //校验学号是否为空
        const rulesSno = (rule, value, callback) => {
            if (this.inputViewSno) {
                callback();
            }
            //使用Axios进行校验
            axios.post(
                this.baseURL + 'sno/check/',
                {
                    sno: value,
                }
            )
                .then((res) => {
                    if (res.data.code === 1) {
                        if (res.data.exsits) {
                            callback(new Error("学号已经存在！"));
                        } else {
                            callback();
                        }
                    } else {
                        callback(new Error("校验异常！"))
                    }
                })
                .catch((err) => {
                    //请求失败
                    console.log(err);
                });
        }

        return {
            msg: 'ajkfhwjk',
            baseURL: 'http://127.0.0.1:8000/',
            students: [],
            selectStudents: [],//选择复选框时触发保存信息的集合
            pageStudents: [],
            inputSearch: '',
            total: 500,
            currentpage: 1,
            pagesize: 10,
            dialogVisible: false,
            dialogTitle: '',
            studentForm: {
                sno: '',
                name: '',
                gender: '',
                birthday: '',
                mobile: '',
                email: '',
                address: '',
                image: '',
                imageUrl: '',
            },
            //标识是否是查看
            inputView: false,
            //标识是否可以编辑学号
            inputViewSno: false,
            rules: {
                sno: [
                    { required: true, message: '学号不能为空！', trigger: 'blur' },
                    { pattern: /^[9][5]\d{3}$/, message: "学号必须是95开头的5位数", trigger: 'blur' },
                    { validator: rulesSno, trigger: 'blur' },
                ],
                name: [
                    { required: true, message: '姓名不能为空！', trigger: 'blur' },
                    { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: "2-5个汉字", trigger: 'blur' },
                ],
                gender: [
                    { required: true, message: '性别不能为空！', trigger: 'blur' },
                ],
                birthday: [
                    { trequired: true, message: '出生日期不能为空！', trigger: 'blur' },
                ],
                mobile: [
                    { required: true, message: '手机号不能为空！', trigger: 'blur' },
                    { pattern: /^[1][356789]\d{9}$/, message: "请输入11位手机号", trigger: 'blur' },
                ],
                email: [
                    { required: true, message: '邮箱不能为空！', trigger: 'blur' },
                    { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "请输入符合规范的邮箱", trigger: 'blur' },
                ],
                address: [
                    { required: true, message: '家庭地址不能为空！', trigger: 'blur' },
                ],
            },
        }
    },
    mounted() {
        //自动加载数据
        this.getStudents();
    },
    methods: {
        //获取所有学生信息
        getStudents: function () {
            //记录this地址
            let that = this
            axios
                .get(that.baseURL + "students/")
                .then(function (res) {
                    //请求成功执行函数
                    if (res.data.code === 1) {
                        //把数据给students
                        that.students = res.data.data;
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            showClose: true,
                            message: '操作成功！',
                            type: 'success'
                        });
                    } else {
                        that.$message({
                            showClose: true,
                            message: '数据加载异常，请联系管理员。',
                            type: 'error'
                        });
                    }
                    //console.log(res);

                })
                .catch(function (err) {
                    console.log(err);
                });
        },
        //获取当前页学生数据
        getPageStudents() {
            this.pageStudents = [];
            for (let i = (this.currentpage - 1) * this.pagesize; i < this.total; i++) {
                //遍历输出到pageStudent
                this.pageStudents.push(this.students[i]);
                if (this.pageStudents.length === this.pagesize) break;
            }

        },
        // 根据ID获取图片image
        getImageBySno(sno){
            for(oneStudent of this.students){
                if(oneStudent.sno==sno){
                    return oneStudent.image;
                }
                
            }
        },
        //查询学生信息
        queryStudents() {
            //使用Ajax请求，使用post请求
            let that = this
            //ajax
            axios
                .post(
                    that.baseURL + "students/query/",
                    {
                        inputstr: that.inputSearch
                    }
                )
                .then(function (res) {
                    if (res.data.code === 1) {
                        //11
                        that.students = res.data.data;
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            showClose: true,
                            message: '操作成功！',
                            type: 'success'
                        });
                    } else {
                        //11
                        that.$message({
                            showClose: true,
                            message: '数据加载异常，请联系管理员。',
                            type: 'error'
                        });
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        },
        //分页时修改每页的行数
        handleSizeChange(size) {
            //修改当前页数据量
            this.pagesize = size;
            //数据重新分页
            this.getPageStudents();
        },
        //调整当前的页码
        handleCurrentChange(pageNum) {
            //修改当前页码
            this.currentpage = pageNum;
            //数据重新分页
            this.getPageStudents();
        },
        getAllStudents() {
            //111
            this.inputSearch = "";
            this.getStudents();
        },
        //添加学生信息
        addStudent() {
            this.dialogVisible = true;
            this.inputView = false;
            //修改标题
            this.dialogTitle = "新增学生信息";
            this.inputViewSno = false;
        },
        //学生详情查看
        viewStudent(row) {
            this.dialogVisible = true;
            //浅拷贝
            //this.studentForm=row;
            //采用深拷贝
            // this.studentForm.sno=row.sno;
            // this.studentForm.name=row.name;
            // this.studentForm.gender=row.gender;
            // this.studentForm.birthday=row.birthday;
            // this.studentForm.mobile=row.mobile;
            // this.studentForm.address=row.address;
            // this.studentForm.email=row.email;
            //方法二
            this.studentForm = JSON.parse(JSON.stringify(row));
            this.dialogTitle = "查看学生信息";
            this.inputView = true;
            this.inputViewSno = true;
            // 获取图片
            this.studentForm.image=this.getImageBySno(row.sno);
            this.studentForm.imageUrl=this.baseURL+'media/'+this.studentForm.image;
        },
        //编辑学生详情
        editStudent(row) {
            this.dialogVisible = true;
            //采用深拷贝
            this.studentForm = JSON.parse(JSON.stringify(row));
            this.dialogTitle = "编辑学生信息";
            this.inputViewSno = true;
            this.inputView = false;
            // 获取图片
            this.studentForm.image=this.getImageBySno(row.sno);
            this.studentForm.imageUrl=this.baseURL+'media/'+this.studentForm.image;
        },
        //学生表单校验
        submitStudentForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 校验通过，进行添加
                    if (this.inputViewSno) {
                        // 修改
                        this.submitEditStudent();

                    } else {
                        // 新增
                        this.submitAddStudent();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //   添加学生信息到数据库
        submitAddStudent() {
            // 定义that
            let that = this;
            // 执行axios
            axios
                .post(that.baseURL + 'add/student/', that.studentForm)
                .then(res => {
                    // 执行成功
                    if (res.data.code === 1) {
                        // 获取学生信息
                        that.students = res.data.data;
                        // 获取数据条数
                        that.total = res.data.data.length;
                        // 获取分页信息
                        that.getPageStudents();
                        that.$message({
                            message: '添加成功！',
                            type: 'success'
                        });
                        that.closeDialogForm('studentForm');
                    } else {
                        // 失败提示
                        that.$message.error(res.data.message);
                    }

                })
                .catch(err => {
                    // 执行失败
                    that.$message({
                        showClose: true,
                        message: '数据加载异常，请联系管理员。',
                        type: 'error'
                    });
                })
        },
        //   修改学生信息到数据库
        submitEditStudent() {
            // 定义that
            let that = this;
            // 执行axios
            axios
                .post(that.baseURL + 'edit/student/', that.studentForm)
                .then(res => {
                    // 执行成功
                    if (res.data.code === 1) {
                        // 获取学生信息
                        that.students = res.data.data;
                        // 获取数据条数
                        that.total = res.data.data.length;
                        // 获取分页信息
                        that.getPageStudents();
                        that.$message({
                            message: '修改成功！',
                            type: 'success'
                        });
                        that.closeDialogForm('studentForm');
                    } else {
                        // 失败提示
                        that.$message.error(res.data.message);
                    }

                })
                .catch(err => {
                    // 执行失败
                    that.$message({
                        showClose: true,
                        message: '数据加载异常，请联系管理员。',
                        type: 'error'
                    });
                })
        },
        // 删除单条数据
        deleteStudent(row) {
            // 确认删除

            this.$confirm('是否确认删除姓名为：' + row.name + '的学生信息', '删除确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 确认删除响应事件
                let that = this;
                axios.post(that.baseURL + 'delete/student/', { sno: row.sno })
                    .then(res => {
                        if (res.data.code === 1) {
                            // 删除成功
                            that.students = res.data.data;
                            // 获取记录数
                            that.total = res.data.data.length;
                            // 获取分页信息
                            that.getPageStudents();
                            that.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        } else {
                            that.$message.error(res.data.message);
                        }


                    })
                    .catch(err => {
                        // 执行失败
                        that.$message({
                            showClose: true,
                            message: '数据删除异常，请联系管理员。',
                            type: 'error'
                        });
                    })

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleDelteStudents(data) {
            this.selectStudents = data;
        },
        // 批量删除数据
        deleteStudents() {
            this.$confirm('是否确认批量删除学生信息', '删除确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 确认删除响应事件
                let that = this;
                axios.post(
                    that.baseURL + 'delete/students/',
                    {
                        students: that.selectStudents
                    }
                )
                    .then(res => {
                        // 处理结果
                        if (res.data.code === 1) {
                            that.students = res.data.data;
                            // 获取记录数
                            that.total = res.data.data.length;
                            // 获取分页信息
                            that.getPageStudents();
                            that.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        } else {
                            that.$message.error(res.data.message);
                        }
                    })
                    .catch(err => {
                        // 执行失败
                        that.$message({
                            showClose: true,
                            message: '数据删除异常，请联系管理员。',
                            type: 'error'
                        });
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 上传头像触发事件
        uploadPicturePost(file){
            let that=this;
            // 定义formdata类
            let fileReq=new FormData();

            fileReq.append('file_name',file.file);
            // 发起请求
            axios(
                {
                    method:'post',
                    url:that.baseURL+'upload/',
                    data:fileReq
                }
            )
            .then(res=>{
                if(res.data.code===1){
                    // 把照片给image
                    that.studentForm.image=res.data.name;
                    // 拼全称
                    that.studentForm.imageUrl=that.baseURL+'media/'+res.data.name;
                }else{
                    that.$message.error(res.data.msg);
                }

            })
            .catch(err => {
                        // 执行失败
                        that.$message({
                            showClose: true,
                            message: '上传图片异常，请联系管理员。',
                            type: 'error'
                        });
                    })
        },
        //关闭详情弹窗
        closeDialogForm(formName) {
            // 重置校验提示信息
            this.$refs[formName].resetFields();
            this.studentForm.sno = '';
            this.studentForm.name = '';
            this.studentForm.gender = '';
            this.studentForm.birthday = '';
            this.studentForm.mobile = '';
            this.studentForm.address = '';
            this.studentForm.email = '';
            this.studentForm.image='';
            this.dialogVisible = false;
            this.inputView = false;
            this.inputViewSno = false;
        }

    },



})

